package com.demo.java.zk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;

import java.util.concurrent.TimeUnit;

public class ZKNode1 {

    public static void main(String[] args) {
        CuratorFramework framework = CuratorFrameworkFactory.builder()
                .connectString("localhost:2181")
                .connectionTimeoutMs(15000)
                .sessionTimeoutMs(60000)
                .retryPolicy(new ExponentialBackoffRetry(5000, Integer.MAX_VALUE))
                .build();
        framework.start();

        String str1 = null;
        try {
            // TODO:// 第一个服务器启动， 在/ocean节点下创建master临时节点成功，data为服务器IP，则标识为master；
            str1 = framework.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                    .forPath("/ocean/master", "node1".getBytes());
            System.out.println("node1 started, current is master node.");
        } catch (Exception e) {
            System.out.println("node1, master ephemeral exists.");
            e.printStackTrace();
        }
        System.out.println("str1: " + str1);

        String str2 = null;
        try {
            // TODO:// 创建 /ocean/ip 临时节点；
            str2 = framework.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                    .forPath("/ocean/node1");
            System.out.println("create ephemeral node1 sucess.");
        } catch (Exception e) {
            System.out.println("node1 ephemeral, master ephemeral exists.");
            e.printStackTrace();
        }
        System.out.println("str1: " + str2);

        // TODO:// 监听ocean子节点的添加与删除, 监控服务器上线下线，
        PathChildrenCache pathChildrenCache = new PathChildrenCache(framework, "/ocean", true);
        try {
            pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
            pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
                @Override
                public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                    System.out.println("==============================");
                    System.out.println(pathChildrenCacheEvent.toString());
                    System.out.println("==============================");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {}
        framework.close();
    }
}
